<?php
	/*
		Convert each page of PDF file into PNG
		@param string $dir_name the path to the repository directory
		@param string $input_file the path to the input PDF file
		@param boolean $isSWF whether the extracted page image should stored as a swf file
		@param boolean $txtSWF whether the page text should be extracted from pdf or swf file
		@return array $result [the average width, height and newpage tags for the template file]
	*/
	function convertPDF($dir_name,$input_file,$isSWF, $txtSWF) {
		//convert each page of pdf into png and get its page size
		$new_input = basename($input_file);
		$width = 0;
		$height = 0;
		$page_input = "";
		
		//get info of each pages in pdf
		$stat = exec($GLOBALS['pdf2swf']." -I ".escapeshellarg($input_file), $outarray, $ret);
		for ($k = 0; $k < count($outarray); $k++) {
			echo "converting ".$k."<br />";
			$line = explode(" ",$outarray[$k]);
			
			$subarray = array();
			
			for ($n = 0; $n < count($line); $n++) {
				$line2 = explode("=",$line[$n]);
				array_push($subarray, $line2[1]);
			}
				
			//get the name for the extracted page image
			$i = $subarray[0];
			$fname = explode(".",$new_input);
			$backFile = $fname[0]."_Page_".$i;
			
			//get the page image
			$output_file = getPDFImage ($isSWF, $input_file, $i, $dir_name, $backFile);
			$page_input = $page_input."<newpage filename=\"".$output_file."\" />\n";
			
			if ($isSWF == false) {
				//grab the png image width and height
				list($png_width, $png_height, $png_type, $png_attr) = getimagesize($dir_name."/".$output_file);
				$subarray[1] = $png_width;
				$subarray[2] = $png_height;
			}
			
			//get the smallest width and height
			if (($width == 0) || ($subarray[1] < $width)) {
				$width = floor($subarray[1]);
			}
			if (($height == 0) || ($subarray[2] < $height)) {
				$height = floor($subarray[2]);
			}
			
			//get the page text
			$str = getPDFText ($isSWF,$txtSWF, $input_file, $i, $dir_name, $backFile);
			$page_input .= "<pagetext>".$str."</pagetext>\n";
		}
		
		//move the pdf file to the repository as well
		copy($input_file, $dir_name."/".$new_input);
		unlink($input_file);
		
		$result = array();
		array_push($result, $width);
		array_push($result, $height);
		array_push($result, $page_input);
		
		return $result;
	}
	
	/*
		Get the page image from the specified pdf file and store it as
		swf or png images
		@param boolean $isSWF     whether we are saving it to swf file
		@param string $input_file the full path to the pdf file
		@param number $pNum       the page number
		@param string $dir_name   the path to go to the book repository
		                          directory
		@param string $backFile   the new file name for the extracted page
	*/
	function getPDFImage ($isSWF, $input_file, $pNum, $dir_name, $backFile) {
		if ($isSWF == true) {
			getSWFFromPDF ($input_file, $pNum, $dir_name."/".$backFile.".swf");
		} else {
			$backFile .= ".png";
			getPNGFromPDF ($input_file, $pNum, $dir_name."/".$backFile);
		}
		return $backFile;
	}
	
	function getPNGFromPDF ($input_file, $pNum, $output_file) {
		$gs_options = escapeshellarg($GLOBALS["ghostscript"]);
		$gs_options .= " -dSAFER -dNOPAUSE -sDEVICE=png16m -r150";
		$gs_options .= " -dDOINTERPOLATE -dTextAlphaBits=4 -dGraphicsAlphaBits=4";
		$gs_options .= " -dFirstPage=".$pNum." -dLastPage=".$pNum;
		$gs_options .= " -sOutputFile=".escapeshellarg($output_file);
		$gs_options .= " -dBATCH ".escapeshellarg($input_file);
		$lstat = exec($gs_options);
	}
	
	/*
		Get the swf page image from the specified pdf file
		@param string $input_file the full path to the pdf file
		@param number $pNum       the page number
		@param string $output_file the full path to the swf file
	*/
	function getSWFFromPDF ($input_file, $pNum, $output_file) {
		$swf_options = escapeshellarg($GLOBALS["pdf2swf"]);
		$swf_options .= " -p ".$pNum." -s insertstop -s zoom=150 -s bboxvars";
		$swf_options .= " -s subpixels=150";
		$swf_options .= " -F ".escapeshellarg($GLOBALS["fontdir"])." -f ";
		$swf_options .= escapeshellarg($input_file)." -o ".escapeshellarg($output_file);
		$lstat = exec($swf_options);
	}
	
	/*
		Grab text from pdf file either using pdftotext or swfstring
		@param boolean $isSWF     whether we are saving page image to swf file
		@param boolean $txtSWF    whether we are using swfstring
		@param string $input_file the full path to the pdf file
		@param number $pNum       the page number
		@param string $dir_name   the path to go to the book repository
		                          directory
		@param string $backFile   the new file name for the extracted page
	*/
	function getPDFText ($isSWF, $txtSWF, $input_file, $pNum, $dir_name, $backFile) {
		$str = "";
		if ($txtSWF == true) {
			//if we haven't create swf from that page, create it first
			$output_file = $dir_name."/".$backFile.".swf";
			if ($isSWF == false) {
				getSWFFromPDF ($input_file, $pNum, $output_file);
			}
			//get the text from the swf file
			$str = getTextFromSWF ($output_file);
			//remove the swf file
			if ($isSWF == false) {
				unlink($output_file);
			}
		} else {
			$txtFile = $dir_name."/".$backFile.".txt";
			$str = getTextFromPDF ($input_file, $pNum, $txtFile);
		}
		
		$str = cleanGrabText($str);
		return $str;
	}
	
	/*
		Grab text for the specified page of the given pdf file
		using pdftotext, and save it temporarily to the specified
		text file
		@param string $input_file the full path to the pdf file
		@param number $pNum       the page number
		@param string $txtFile    the full path to the text file
	*/
	function getTextFromPDF ($input_file, $pNum, $txtFile) {
		//get text from pdf and save it to a text file
		$pdf_options = escapeshellarg($GLOBALS["pdftotext"]);
		$pdf_options .= " -f ".$pNum." -l ".$pNum;
		$pdf_options .= " ".escapeshellarg($input_file);
		$pdf_options .= " ".escapeshellarg($txtFile);
		$pdf_text = shell_exec($pdf_options);
		//get the text from the text file
		$str = file_get_contents($txtFile);
		//delete the text file
		unlink($txtFile);
		return $str;
	}
	
	/*
		Grab text from the specified swf file
		@param string $output_file the full path to the swf file
	*/
	function getTextFromSWF ($output_file) {
		//get text from swf
		$swf_options = escapeshellarg($GLOBALS["swfstring"]);
		$swf_options .= " ".escapeshellarg($output_file);
		$str = shell_exec($swf_options);
		return $str;
	}
	
	/*
		Process the text grabbed from pdf or swf file
		@param string $str the grabbed text
	*/
	function cleanGrabText ($str) {
		if (strlen($str) > 0) {
			//remove non iso character
			$str = iconv('UTF-8', 'ISO-8859-1//IGNORE//TRANSLIT', $str);
			$str = htmlspecialchars($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
			$str = str_replace("\x", "&@", $str);
			$str = preg_replace("/&@[0-9a-z][0-9a-z]/i","",$str);
			//to make sure that they are not considered as a tag
			$str = str_replace("<","&lt;",$str);
			$str = str_replace(">","&gt;",$str);
		}
		
		return $str;
	}
	
	/*
		Convert each video and audio file into SWF
		@param string $dir_name the path to the repository directory
		@param string $input_file the path to the input media file
		@return array $result [the average width, height and newpage tags for the template file]
	*/
	function convertMedia($dir_name,$input_file) {
		$fname = basename($input_file);
		$list = explode(".",$fname);
		$height = 80;
		if (strcmp(strtolower($list[1]),"flv") == 0)
			$height = 200;
		$media_file = $list[0]."@".$list[1];
		
		//copy the converted swfs to the repository directory
		copy("ExampleBooks/mediaplayer.swf",$dir_name."/".$media_file.".swf");
		copy($input_file, $dir_name."/".$fname);
		unlink($input_file);
		$page_input = "<newpage />\n<newpage />\n";
		$page_input = $page_input."<newpage filename=\"".$media_file."\" />\n";
		$page_input = $page_input."<newpage />\n<newpage />\n<newpage />\n";
		
		$result = array();
		array_push($result, 300);
		array_push($result, $height);
		array_push($result, $page_input);
		
		return $result;
	}

	/*
		Move the swf, png or jpg to the repository directory
		@param string $dir_name the path to the repository directory
		@param string $input_file the path to the input image file
		@return array $result [the average width, height and newpage tags for the template file]
	*/
	function convertImage($dir_name, $input_file) {
		list($width, $height, $type, $attr) = getimagesize($input_file);//get width and height
		$fname = basename($input_file);
		copy($input_file, $dir_name."/".$fname);
		unlink($input_file);
		$list = explode(".",$fname);
		$nname = $list[0];
		if (strcmp(strtolower($list[1]),"swf") != 0) {
			$nname = $nname.".".$list[1];
		}
		$page_input = "<newpage />\n<newpage />\n";
		$page_input = $page_input."<newpage filename=\"".$nname."\" />\n";
		$page_input = $page_input."<newpage />\n<newpage />\n<newpage />\n";
		
		$result = array();
		array_push($result, $width);
		array_push($result, $height);
		array_push($result, $page_input);
		
		return $result;
	}
	
	/*
		Check whether the newly added non-text files needs to be appended
		to the existing template file.
		@param string $folder_name the directory path to the template file
		@param array $pg_images [the average width, height and newpage tags for the template file]
		@param boolean $isImage whether the file is a page image
	 */
	function appendTemplateMedia($folder_name, $pg_images,$isImage) {
		//get all the image list in the template file
		$data = file_get_contents($folder_name."/".$GLOBALS["book"]);
		preg_match_all('/<img[^>]*src="([^"]+)"[^>]+>/i', $data, $img_list, PREG_SET_ORDER);
		
		$add_img = str_replace("<newpage />\n","",$pg_images[2]);
		if (count($img_list) > 0) {
			//get all the page image file name
			preg_match_all('/<newpage[^>]*filename="([^"]+)"[^>]+>/i', $pg_images[2], $pg_matches, PREG_SET_ORDER);
			$add_img = "";
			foreach ($pg_matches as $pg_val) {
				$found = false;
				for ($i = 0; (($i < (count($img_list) - 1)) && ($found == false)); $i = $i + 2) {
					if (strcmp("repository/".$pg_val[1], $img_list[$i + 1]) == 0) {
						//update the image width and height in the template file
						list($width, $height, $type, $attr) = getimagesize($img_list[$i + 1]);
						$new_img_tag = "<img src=\"".$img_list[$i+1]."\" width=\"".$width."\" height=\"".$height."\" />";
						$data = str_replace($img_list[$i], $new_img_tag, $data);
						$found = true;
					}
				}
				if ($found == false) {
					//later append as page image
					$add_img = $pg_val[0]."\n";
				}
			}
		}
		
		if ($isImage == true) {
			//update the page image
			$data = str_ireplace("<metadata name=\"ispageimage\">false</metadata>",
								"<metadata name=\"ispageimage\">true</metadata>", $data);
		}
		
		if (strlen($add_img) > 0) {
			//update the page size
			preg_match_all('/<metadata name="pagesize">(\d+)x(\d+)<\/metadata>/i', $data, $matches, PREG_SET_ORDER);
		
			$pw = (int) $pg_images[0];
			$ph = (int) $pg_images[1];
			$i = 0;
			foreach ($matches as $val) {
				$pw = max((int) $val[1], $pw);
				$ph = max((int) $val[2], $ph);
				$i++;
				if ($i == count($matches)) {
					//change with the new page size
					$new_meta = "<metadata name=\"pagesize\">".$pw."x".$ph."</metadata>";
					$data = str_replace($val[0], $new_meta, $data);
				} else {
					//remove other page size definition
					$data = str_replace($val[0], "", $data);
				}
			}
			
			//append to the end of template
			//let's assume that at the end of template file there will always be </html>
			//and there's only one
			preg_match_all('/((<\/section>[\s\r\n]*)+(<\/body>)?[\s\r\n]*)<\/html>/i', $data, $tag_matches, PREG_SET_ORDER);
			foreach ($tag_matches as $tag_val) {
				$data = str_replace($tag_val[0], $add_img.$tag_val[0], $data);
			}
			if (count($tag_matches) == 0) {
				preg_match_all('/((<newpage \/>[\s\r\n]*){3}(<\/body>)?[\s\r\n]*)<\/html>/i', $data, $tag_matches, PREG_SET_ORDER);
				if (count($tag_matches) == 0) {
					$data = str_replace("</html>", $add_img."</html>", $data);
				} else {
					foreach ($tag_matches as $tag_val) {
						$new_tag = substr($tag_val[0], strlen("<newpage />"));
						$data = str_replace($tag_val[0], $add_img.$new_tag, $data);
					}
				}
			}
		}
		
		//save the template file
		$html_file = $GLOBALS["book"];
		$file = modifyFile($folder_name."/".$html_file,"w");
		if (!$file) die ("cannot open the file");
		fwrite($file, $data);
		fclose($file);
	}
	
	/*
		Create the template file
		@param string $folder_name the directory path to the template file
		@param string $dir_name the name of the source file
		@param array $pg_images [the average width, height and newpage tags for the template file]
		@param boolean $isImage whether the file is a page image
	*/
	function createTemplate($folder_name,$dir_name,$pg_images,$isImage) {
		// get page size
		$page_size = $pg_images[0]."x".$pg_images[1];
						
						
		// create the book structure file
		$html_input = "<html>\n<title>".$dir_name."</title>\n<description>\n";
		$html_input .= "<!-- Please do not remove filename and pagefolder metadata -->\n";
		$html_input .= "<metadata name=\"filename\">".$dir_name."</metadata>\n";
		$html_input .= "<metadata name=\"pagefolder\">repository</metadata>\n";
		$html_input .= "<metadata name=\"startnumbering\">1</metadata>\n";
		$html_input .= "<metadata name=\"pagesize\">".$page_size."</metadata>\n";
		$html_input .= "<metadata name=\"zoomstyle\">fit book</metadata>\n";
		if ($isImage == true)
			$html_input .= "<metadata name=\"ispageimage\">true</metadata>\n";
		$html_input .= "</description>\n";
		$html_input .= $pg_images[2];
		$html_input .= "</html>\n";
		
		//save the template file
		$html_file = $GLOBALS["book"];
		$file = modifyFile($folder_name."/".$html_file,"w");
		if (!$file) die ("cannot open the file");
		fwrite($file, $html_input);
		fclose($file);
	}
?>